package com.atguigu.gmall.list.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.list.dao.GoodsDao;
import com.atguigu.gmall.list.service.ListService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.BaseTrademark;
import com.atguigu.gmall.model.product.SkuAttrValue;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ListServiceImpl implements ListService {
    @Autowired
    private GoodsDao goodsDao;//增删改性能非常好
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired//默认 优化使用数据...
    private RestHighLevelClient restHighLevelClient;//高级别客户端 查询性能最好
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;//高级别客户端 查询性能好
    @Autowired
    private RedisTemplate redisTemplate;

    //上架
    @Override
    public void onSale(Long skuId) {
        //TODO 异步编排
        Goods goods = new Goods();
        //1:查询skuInfo
        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
        goods.setId(skuInfo.getId());
        goods.setTitle(skuInfo.getSkuName());
        goods.setDefaultImg(skuInfo.getSkuDefaultImg());
        goods.setPrice(skuInfo.getPrice().doubleValue());
        //2:时间 添加索引的时间
        Calendar calendar = Calendar.getInstance();
        goods.setCreateTime(calendar.getTime());
        //3:品牌
        BaseTrademark baseTrademark = productFeignClient.getBaseTrademark(skuInfo.getTmId());
        goods.setTmId(baseTrademark.getId());
        goods.setTmName(baseTrademark.getTmName());
        goods.setTmLogoUrl(baseTrademark.getLogoUrl());
        //4:一二三级分类
        BaseCategoryView baseCategoryView = productFeignClient.getBaseCategoryView(skuInfo.getCategory3Id());
        goods.setCategory1Id(baseCategoryView.getCategory1Id());
        goods.setCategory1Name(baseCategoryView.getCategory1Name());
        goods.setCategory2Id(baseCategoryView.getCategory2Id());
        goods.setCategory2Name(baseCategoryView.getCategory2Name());
        goods.setCategory3Id(baseCategoryView.getCategory3Id());
        goods.setCategory3Name(baseCategoryView.getCategory3Name());
        //5:平台属性集合
        List<SkuAttrValue> skuAttrValueList = productFeignClient.getSkuAttrValueAndAttrAndAttrValue(skuId);
        List<SearchAttr> searchAttrList = skuAttrValueList.stream().map(skuAttrValue -> {
            SearchAttr searchAttr = new SearchAttr();
            searchAttr.setAttrId(skuAttrValue.getBaseAttrInfo().getId());
            searchAttr.setAttrName(skuAttrValue.getBaseAttrInfo().getAttrName());
            searchAttr.setAttrValue(skuAttrValue.getBaseAttrValue().getValueName());
            return searchAttr;
        }).collect(Collectors.toList());
        goods.setAttrs(searchAttrList);
        //保存
        goodsDao.save(goods);
    }

    //下架  客户端删除麻烦 故用ElasticsearchRepository
    @Override
    public void cancelSale(Long skuId) {
        goodsDao.deleteById(skuId);
    }

    //商品热度评分 加分
    @Override
    public void incrHotScore(Long skuId, Integer score) {
        /**ES查询快 增删改慢 故不要频繁的增删改   考虑先保存分数到缓存中 积累到10的倍数 更新ES分数
         并发操作 因为好多人在商城浏览 关注商品 添加购物车 购买等 缓存
         不加锁了 加分不是重点业务还麻烦 本次将使用ZSet类型
         */
        //仍然存在多线程问题
//        Double hostScore = redisTemplate.opsForZSet().score("hostScore", skuId);
//        Double  AllhostScore= hostScore+score;
//        redisTemplate.opsForZSet().add("hostScore",skuId,AllhostScore);
        //一行顶三行且无多线程问题 单线程+多路IO复用 保证原子性
        Double totalScore = redisTemplate.opsForZSet().incrementScore("hostScore", skuId, score);
        if (totalScore % 10 == 0) {//每当热点达到10的倍数就更新ES,可能20时更新,可能50时更新,如48>53是不会更新的
            //1: 查询ES
            Optional<Goods> byId = goodsDao.findById(skuId);
            Goods goods = byId.get();
            //2: 加指定的分
            goods.setHotScore(Math.round(totalScore));//四舍五入
            //3: 更新ES  底层:先删除 再添加 Lucene
            goodsDao.save(goods);
        }
        System.out.println("当前总分:" + totalScore);
    }

    //开始搜索
    @Override
    public SearchResponseVo search(SearchParam searchParam) {
        //1:创建索引请求对象  searchRequest   100行
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        //2:执行搜索
        SearchResponse searchResponse = null;
        try {
            searchResponse =
                    restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3:对返回值SearchResponse 进行结果解析  100行
        SearchResponseVo vo = parseSearchResponse(searchResponse);
        vo.setPageNo(searchParam.getPageNo());
        vo.setPageSize(searchParam.getPageSize());
        //总页数  = （总条数 + 每页数 - 1）/每页数
        //            13        5
        long totalPages = (vo.getTotal() + vo.getPageSize() - 1) / vo.getPageSize();
        vo.setTotalPages(totalPages);
        return vo;
    }

    //对返回值SearchResponse 进行结果解析
    private SearchResponseVo parseSearchResponse(SearchResponse searchResponse) {
        SearchResponseVo vo = new SearchResponseVo();
        //1:总条数
        SearchHits hits = searchResponse.getHits();
        long totalHits = hits.totalHits;
        System.out.println("总条数：" + totalHits);
        vo.setTotal(totalHits);
        //2:商品集合
        SearchHit[] hits1 = hits.getHits();
        List<Goods> goodsList = Arrays.stream(hits1).map(h -> {
            Goods goods = JSONObject.parseObject(h.getSourceAsString(), Goods.class);
            Map<String, HighlightField> highlightFields = h.getHighlightFields();
            if (null != highlightFields && highlightFields.size() > 0) {
                HighlightField title = highlightFields.get("title");
                String s = title.getFragments()[0].toString();
                goods.setTitle(s);
            }
            return goods;
        }).collect(Collectors.toList());
        vo.setGoodsList(goodsList);
        //3:品牌集合
        Aggregations aggregations = searchResponse.getAggregations();
        ParsedLongTerms aggTmId = aggregations.get("aggTmId");
        List<SearchResponseTmVo> trademarkList = aggTmId.getBuckets().stream().map(bucket -> {
            SearchResponseTmVo tmVo = new SearchResponseTmVo();
            //ID
            tmVo.setTmId(((Terms.Bucket) bucket).getKeyAsNumber().longValue());
            //品牌的名称
            ParsedStringTerms aggTmName = ((Terms.Bucket) bucket).getAggregations().get("aggTmName");
            tmVo.setTmName(aggTmName.getBuckets().get(0).getKeyAsString());
            //品牌的Logo
            ParsedStringTerms aggTmLogoUrl = ((Terms.Bucket) bucket).getAggregations().get("aggTmLogoUrl");
            tmVo.setTmLogoUrl(aggTmLogoUrl.getBuckets().get(0).getKeyAsString());
            return tmVo;
        }).collect(Collectors.toList());
        vo.setTrademarkList(trademarkList);
        //4:平台属性集合
        ParsedNested aggAttrs = aggregations.get("aggAttrs");
        ParsedLongTerms aggAttrId = aggAttrs.getAggregations().get("aggAttrId");
        List<SearchResponseAttrVo> attrsList =
                aggAttrId.getBuckets().stream().map(bucket -> {
                    SearchResponseAttrVo attrVo = new SearchResponseAttrVo();
                    //ID
                    attrVo.setAttrId(((Terms.Bucket) bucket).getKeyAsNumber().longValue());
                    //平台属性名称
                    ParsedStringTerms aggAttrName = ((Terms.Bucket) bucket).
                            getAggregations().get("aggAttrName");
                    attrVo.setAttrName(aggAttrName.getBuckets().get(0).getKeyAsString());
                    //平台属性值集合
                    ParsedStringTerms aggAttrValue = ((Terms.Bucket) bucket)
                            .getAggregations().get("aggAttrValue");
                    List<String> attrValueList = aggAttrValue.getBuckets().stream()
                            .map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
                    attrVo.setAttrValueList(attrValueList);
                    return attrVo;
                }).collect(Collectors.toList());
        vo.setAttrsList(attrsList);
        return vo;
    }

    //创建索引请求对象
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //构建组合对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //1：关键词
        String keyword = searchParam.getKeyword();
        if (!StringUtils.isEmpty(keyword)) {
            //有   match :    1)先分词     我是一个好人  我   是   一个   好人
            //               2）相当于 mysql  where
            //                         name like ‘%我%’ OR
            //                         name like ‘%是%’ OR
            //                         name like ‘%一个%’ OR
            //                         name like ‘%好人%’
            // must  must_not  should
            // and     not        or
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("title", keyword).operator(Operator.AND));
        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());//查询全部
        }
        //2：品牌    品牌ID:品牌的名称  过滤条件
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)) {
            // mysql  where name =  华为
            String[] t = StringUtils.split(trademark, ":");
            boolQueryBuilder.filter(QueryBuilders.termQuery("tmId", t[0]));
        }
        //3、三级分类 过滤条件
        Long category1Id = searchParam.getCategory1Id();
        if (null != category1Id) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id", category1Id));
        }
        Long category2Id = searchParam.getCategory2Id();
        if (null != category2Id) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id", category2Id));
        }
        Long category3Id = searchParam.getCategory3Id();
        if (null != category3Id) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id", category3Id));
        }
        //4: 平台属性   （难）  过滤条件
        //  http://url?props=平台ID:平台值:平台属性名
        String[] props = searchParam.getProps();
        if (null != props && props.length > 0) {
            //儿子的组合对象
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            for (String prop : props) {
                String[] p = prop.split(":");
                if (null != p && p.length == 3) {
                    BoolQueryBuilder subBoolQuery = QueryBuilders.boolQuery();
                    subBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", p[0]));
                    //subBoolQuery.must(QueryBuilders.termQuery("attrs.attrName",p[2]));
                    subBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue", p[1]));
                    boolQuery.must(QueryBuilders.nestedQuery("attrs", subBoolQuery, ScoreMode.None));
                }
            }
            boolQueryBuilder.filter(boolQuery);
        }
        searchSourceBuilder.query(boolQueryBuilder);
        //5:排序   1:desc 1:asc 2:desc 2:asc
        String order = searchParam.getOrder();
        String field = "hotScore";//默认综合  排序
        if (!StringUtils.isEmpty(order)) {
            String[] o = order.split(":");
            switch (o[0]) {
                case "1":
                    break;
                case "2":
                    field = "price";
                    break;
                case "3":
                    field = "createTime";
                    break;
            }
            searchSourceBuilder.sort(field, "asc".equalsIgnoreCase(o[1]) ? SortOrder.ASC : SortOrder.DESC);
        } else {
            //默认排序
            searchSourceBuilder.sort(field, SortOrder.DESC);
        }
        //6:分页   limit  开始行 , 每页数
        Integer pageNo = searchParam.getPageNo();
        Integer pageSize = searchParam.getPageSize();
        searchSourceBuilder.from((pageNo - 1) * pageSize);//
        searchSourceBuilder.size(pageSize);//
        //7:高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title")
                .preTags("<font style='color:red'>")  //前缀
                .postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);
        //8:聚合
        //8.1 : 品牌聚合
        searchSourceBuilder.aggregation(
                AggregationBuilders.terms("aggTmId").field("tmId")
                        .subAggregation(AggregationBuilders.terms("aggTmName").field("tmName"))
                        .subAggregation(AggregationBuilders.terms("aggTmLogoUrl").field("tmLogoUrl")));
        //8.2  平台属性聚合
        searchSourceBuilder.aggregation(AggregationBuilders.nested("aggAttrs", "attrs")
                .subAggregation(AggregationBuilders.terms("aggAttrId").field("attrs.attrId")
                        .subAggregation(AggregationBuilders.terms("aggAttrValue").field("attrs.attrValue"))
                        .subAggregation(AggregationBuilders.terms("aggAttrName").field("attrs.attrName"))));

        System.out.println("DSL:" + searchSourceBuilder.toString());
        searchRequest.source(searchSourceBuilder);
        //设置索引库的名称
        searchRequest.indices("goods");
        //设置 type
        //searchRequest.types("info","hhss");
        return searchRequest;
    }
}
